#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"

using task_t =std::function<void()>;

class Route
{
public:
    Route()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }

    void CheckOnline(InetAddr &who)
    {
        LockGuard lockguard(&_mutex);
        for (auto &user : _online_user)
        {
            if (user == who)
            {
                LOG(DEBUG, "%s is exist\n", who.AddrStc().c_str());
                return;
            }
        }
        LOG(DEBUG, "%s is not exist\n", who.AddrStc().c_str());
        _online_user.push_back(who);
    }

    void Offline(InetAddr &who)
    {
        LockGuard lockguard(&_mutex);

        auto iter = _online_user.begin();
        for (; iter != _online_user.end(); iter++)
        {
            if (*iter == who)
            {
                LOG(DEBUG, "%s is offline", who.AddrStc().c_str());
                _online_user.erase(iter);
                break;
            }
        }
    }

    void ForwardHelper(int sockfd, const std::string &message, InetAddr &who)
    {
        LockGuard lockguard(&_mutex);
        std::string send_message="["+who.AddrStc()+"]#"+message;
        for(auto &user:_online_user)
        {
            struct sockaddr_in peer=user.Addr();
            LOG(DEBUG,"message to %s; message is %s",user.AddrStc().c_str(),message.c_str());
            sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&peer,sizeof(peer));
        }
    }

    void Forward(int sockfd, const std::string &message, InetAddr &who)
    {
        CheckOnline(who);

        if (message == "QUIT" || message == "Q")
            Offline(who);
        
        task_t t=std::bind(Route::ForwardHelper,this,sockfd,message,who);
        threadpool<task_t>::GetInstance()->Equeue(t);
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};